<?php

namespace App\Repositories\Biz;

use Prettus\Repository\Eloquent\BaseRepository as Repository;

class ShopRepository extends Repository
{

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    public function model()
    {
        return 'App\Models\Biz\Shop';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($query = '')
    {
        $staff = \Auth::guard('admin')->user();

        if (!$query) {
            $result = $this->current($staff)->orderBy('id', 'desc')->paginate(10);
        } else {
            $result = $this->current($staff)->where('name', 'like', "%$query%")->paginate(1);
        }

        return $result;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($request)
    {
        $fillable = $this->model->getFillable();
        
        \DB::beginTransaction();
        try {
            $shop = $this->create($request->only($fillable));

            if(!!$shop){
                $account = \App\Models\Biz\Account::create([
                    'shop_id'=>$shop->id,
                    'passwd'=> \Hash::make(DEFAULT_PASSWORD),
                ]);
            }

            \DB::commit();

            return responseSuccess('新增门店成功');

        } catch (\Exception $e) {
            \DB::rollback();

            return responseFail(500, '新增门店失败');
        }
    }


    public function shops($request)
    {
        $query = $request->term;

        //匹配到全数字，按手机查找
        if (preg_match('/^\d+$/i', $query)) {
            if (strlen($query) == 5) {
                $result = $this->findWhere(array(['id', '=', "$query"]));
            }
        }
        //未匹配到数字，按姓名查找
        else {
            $result = $this->findWhere(array(['name', 'like', "%$query%"]));
        }

        return $result->toJson();
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
